import { Form } from "@douyinfe/semi-ui";
import React from "react";

const FormInput = Form.Input;
const FormCheckbox = Form.Checkbox;

interface FormValues {
  filterText: string;
  inStockOnly: boolean;
}
interface SearchBarProps extends FormValues {
  filterTextChange: (filterText: string) => void;
  inStockOnlyChange: (inStockOnly: boolean) => void;
}
/**
 * (蓝色)获取用户输入
 * @props SearchBarProps
 * @returns 函数组件
 */
const SearchBar: React.FC<SearchBarProps> = ({ filterText, inStockOnly, filterTextChange, inStockOnlyChange }) => {
  /**
   * 对象方法映射mapped
   */
  const mappedFunc = new Map<keyof FormValues, (value: any) => void>([
    ["filterText", filterTextChange],
    ["inStockOnly", inStockOnlyChange]
  ]);

  const onValueChange = (_: FormValues, changedValue: Partial<FormValues>) => {
    for (const [key, value] of Object.entries(changedValue)) {
      if (mappedFunc.has(key as keyof FormValues)) {
        mappedFunc.get(key as keyof FormValues)?.(value);
      }
    }
  };

  return (
    <section>
      <h3>SearchBar</h3>
      <Form<FormValues> initValues={{ filterText, inStockOnly }} onValueChange={onValueChange}>
        <FormInput noLabel field="filterText" placeholder="Search..." style={{ width: 250 }} />
        <FormCheckbox noLabel field="inStockOnly">
          Only show products in stock
        </FormCheckbox>
      </Form>
    </section>
  );
};
export default SearchBar;
